#include "oasis.h"
#include "ui_oasis.h"
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QGraphicsProxyWidget>
#include <QDebug>

oasis::oasis(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::oasis)
{
    ui->setupUi(this);

    db_init();

    // ====== 1. 创建GIF背景 ======
    movie = new QMovie(":/new/prefix1/Resource/login.gif");
    bgLabel = new QLabel(this);
    bgLabel->setMovie(movie);
    movie->start();

    // 关键修改：增加缩放比例至90%
    bgLabel->setScaledContents(true);
    bgLabel->resize(this->size() * 1.1);  // 放大10%

    // 设置GIF原始尺寸更大
    if(movie->isValid()) {
        movie->setScaledSize(this->size() * 1.2);  // 放大原始尺寸20%
    }

    // 位置居中显示
    bgLabel->move((this->width() - bgLabel->width())/2,
                 (this->height() - bgLabel->height())/2);

    // 透明设置
    bgLabel->setAttribute(Qt::WA_TranslucentBackground);
    bgLabel->setStyleSheet("background: transparent;");
    this->setAttribute(Qt::WA_TranslucentBackground);

    // ====== 2. 调整遮罩层透明度 ======
    mask = new QWidget(this);
    mask->setStyleSheet("background-color: rgba(0,0,0,0.3);"); // 透明度改为30%
    mask->resize(this->size());
    mask->lower();

    // ====== 3. 按钮层级和样式优化 ======

    // ====== 4. 初始化农场窗口 ======
    farm = new FarmDiaryWindow;
    connect(farm,&FarmDiaryWindow::exit,this,[=](){
        this->show();
    });

    // ====== 创建登录面板 ======
     loginPanel = new QWidget(this);
     loginPanel->setFixedSize(350, 300);

     // 设置半透明磨砂效果
     loginPanel->setStyleSheet(
         "background-color: rgba(50, 50, 50, 150);"
         "border-radius: 15px;"
         "border: 1px solid rgba(255, 255, 255, 100);"
     );

     // 创建布局
     QVBoxLayout *mainLayout = new QVBoxLayout(loginPanel);
     mainLayout->setAlignment(Qt::AlignCenter);
     mainLayout->setSpacing(20);
     mainLayout->setContentsMargins(30, 30, 30, 30);

     // 标题
     titleLabel = new QLabel("绿洲农场日记");
     titleLabel->setStyleSheet("color: white; font-size: 24px; font-weight: bold;");
     titleLabel->setAlignment(Qt::AlignCenter);
     mainLayout->addWidget(titleLabel);

     // 用户名输入框
     usernameEdit = new QLineEdit();
     setupInputField(usernameEdit, "用户名");
     mainLayout->addWidget(usernameEdit);

     // 密码输入框
     passwordEdit = new QLineEdit();
     setupInputField(passwordEdit, "密码");
     passwordEdit->setEchoMode(QLineEdit::Password);
     mainLayout->addWidget(passwordEdit);

     // 按钮布局
     QHBoxLayout *buttonLayout = new QHBoxLayout();
     buttonLayout->setSpacing(15);

     loginButton = new QPushButton("登 录");
     setupButton(loginButton);
     buttonLayout->addWidget(loginButton);

     registerButton = new QPushButton("注 册");
     setupButton(registerButton);
     buttonLayout->addWidget(registerButton);

     mainLayout->addLayout(buttonLayout);

     // 连接信号槽
     connect(loginButton, &QPushButton::clicked, this, &oasis::onLoginClicked);
     connect(registerButton, &QPushButton::clicked, this, &oasis::onRegisterClicked);

     // 将登录面板置于遮罩层上方
     loginPanel->raise();
}

oasis::~oasis()
{
    delete ui;

    movie->stop();    // 停止动画
    delete movie;     // 释放资源
    delete bgLabel;   // 删除背景标签
    delete mask;      // 删除遮罩层
}

// 设置输入框样式
void oasis::setupInputField(QLineEdit *field, const QString &placeholder)
{
    field->setPlaceholderText(placeholder);
    field->setStyleSheet(
        "background-color: rgba(255, 255, 255, 150);"
        "border: 1px solid rgba(0, 0, 0, 50);"
        "border-radius: 8px;"
        "padding: 10px;"
        "font-size: 14px;"
    );
    field->setMinimumHeight(40);
}

// 设置按钮样式
void oasis::setupButton(QPushButton *button)
{
    button->setStyleSheet(
        "QPushButton {"
        "   background-color: rgba(70, 130, 180, 200);"
        "   color: white;"
        "   border-radius: 8px;"
        "   padding: 10px 20px;"
        "   font-size: 14px;"
        "   font-weight: bold;"
        "}"
        "QPushButton:hover {"
        "   background-color: rgba(65, 105, 225, 220);"
        "}"
        "QPushButton:pressed {"
        "   background-color: rgba(30, 144, 255, 200);"
        "}"
    );
    button->setMinimumHeight(40);
    button->setCursor(Qt::PointingHandCursor);
}

void oasis::onLoginClicked()
{
    QString username = usernameEdit->text().trimmed();
    QString password = passwordEdit->text();

    // 简单的输入验证
    if(username.isEmpty() || password.isEmpty()) {
        QMessageBox::warning(this, "输入错误", "用户名和密码不能为空");
        return;
    }

    if(db_select(username,password) == false){
        QMessageBox::warning(this, "错误", "用户名或密码错误");
        return;
    }

    // 验证成功后的操作
    QMessageBox::information(this, "登录成功", "欢迎回来，" + username);
    farm->oa_username = username;
    farm->oa_password = password;
    farm->updateProfileData();
    this->hide();
    farm->show();
}

void oasis::onRegisterClicked()
{
    QString username = usernameEdit->text().trimmed();
    QString password = passwordEdit->text();

    if(username.isEmpty() || password.isEmpty()) {
        QMessageBox::warning(this, "输入错误", "用户名和密码不能为空");
        return;
    }

    if(db_select_u(username) == true){
        QMessageBox::warning(this, "警告", "用户名重命名");
        return;
    }

    if(db_insert(username,password) == true){
       // 可以扩展为打开注册窗口
       QMessageBox::information(this, "注册功能", "注册成功");
       // 清空输入框
       usernameEdit->clear();
       passwordEdit->clear();
    }
}

void oasis::resizeEvent(QResizeEvent *event)
{
    QWidget::resizeEvent(event);
    const QSize newSize = event->size();

    // 背景放大110%并居中
    bgLabel->resize(newSize * 1.1);
    bgLabel->move((newSize.width() - bgLabel->width())/2,
                 (newSize.height() - bgLabel->height())/2);

    // 更新GIF原始尺寸（保持高清）
    if(movie->isValid()) {
        movie->setScaledSize(newSize * 1.2); // 动态调整原始尺寸
    }

    // 登录面板居中显示
    if(loginPanel) {
        loginPanel->move(
            (newSize.width() - loginPanel->width()) / 2,
            (newSize.height() - loginPanel->height()) / 2
        );
    }

    // 遮罩层保持全屏
    mask->resize(newSize);
}

void oasis::db_init()
{
    if(QSqlDatabase::contains("qt_sql_default_connection")) {
        db = QSqlDatabase::database("qt_sql_default_connection");
    } else {
        db = QSqlDatabase::addDatabase("QSQLITE");
        db.setDatabaseName("usr.db");
    }

    if(!db.open()) {
        qCritical() << "DB open error:" << db.lastError().text();
        QMessageBox::critical(this, "致命错误", "数据库初始化失败");
    } else {
        QSqlQuery query;
        if(!query.exec("CREATE TABLE IF NOT EXISTS usr(name TEXT PRIMARY KEY, passwd TEXT)")) {
            qCritical() << "Create table error:" << query.lastError().text();
        }
    }
    qDebug() << "当前工作目录：" << QDir::currentPath();
}

bool oasis::db_insert(QString name, QString pswd)
{
    QSqlQuery query(db);
    query.prepare("INSERT INTO usr(name, passwd) VALUES (:name, :passwd)");
    query.bindValue(":name", name);
    query.bindValue(":passwd", pswd);

    if(!query.exec()) {
        qDebug() << "insert failed:" << query.lastError().text();
        return false;
    }
    return true;
}

bool oasis::db_select(QString name, QString pswd)
{
    QSqlQuery query(db);
    query.prepare("SELECT * FROM usr WHERE name = :name AND passwd = :passwd");
    query.bindValue(":name", name);
    query.bindValue(":passwd", pswd);

    if(!query.exec()) {
        qDebug() << "select failed:" << query.lastError().text();
        return false;
    }
    return query.next();
}

bool oasis::db_select_u(QString name)
{
    QSqlQuery query(db);
    query.prepare("SELECT * FROM usr WHERE name = :name");
    query.bindValue(":name", name);

    if(!query.exec()) {
        qDebug() << "select failed:" << query.lastError().text();
        return false;
    }
    return query.next(); // 存在用户返回true
}

